<template>
  <!-- 已登录状态 -->
  <div v-if="logined">
    <div class="mine-container">
      <!-- 头像和用户名 -->
      <div class="person-center">
        <h3>个人中心</h3>
        <div class="person-message">
          <img :src="avatarUrl || defaultAvatar" alt="tou">
          <h4>{{user.nickname}}</h4>
        </div>
      </div>
      <!-- 钱包 -->
      <div class="money">
        <div class="money-title"><img src="../../assets/images/qianbao.png" alt=""><span class="bao">我的钱包</span><img src="../../assets/images/qianbao.png" alt=""></div>
        <div class="money-body">
          <button class="addin" @click="showRechargeDialog">充值</button>
          <div class="money-center">
            <div class="money-left">{{ user.balance }}</div>
            <div class="my">我的余额</div>
          </div>
        <button class="putout" @click="showWithdrawDialog">提现</button>
      </div>
      </div>
      <div class="person-function">
        <!-- 编辑个人信息 -->
        <div class="function-item" @click="gotoPersonal">
          <img src="../../assets/images/编辑.png" alt="">
          <span>编辑个人信息</span>
          <img src="../../assets/images/fangxiang-you.png" alt="">
        </div>
        <!-- 地址设置 -->
        <div class="function-item" @click="gotoAddress">
          <img src="../../assets/images/dizhi.png" alt="">
          <span>地址设置</span>
          <img src="../../assets/images/fangxiang-you.png" alt="">
        </div>
        <!-- 意见反馈 -->
        <div class="function-item" @click="gotoFeedback">
          <img src="../../assets/images/意见反馈.png" alt="">
          <span>意见反馈</span>
          <img src="../../assets/images/fangxiang-you.png" alt="">
        </div>
        <!-- 退出登录 -->
        <div class="function-item" @click="logout">
          <img src="../../assets/images/tuichudenglu.png" alt="">
          <span>退出登录</span>
          <img src="../../assets/images/fangxiang-you.png" alt="">
        </div>
      </div>
  </div>
  </div>

  <!-- 未登录状态 -->
  <div  class="unlogin" v-else>
    <img src="../../assets/images/未登录-头像.png" alt="">
    <h3>暂未登录</h3>
    <div class="des">快去登录，迫不及待与你相见啦~</div>
    <button @click="gotologin">立即登录</button>
  </div>

   <!-- 充值弹窗 -->
   <div v-if="showRecharge" class="dialog-wrapper">
    <div class="dialog-background" @click="hideRechargeDialog"></div>
    <div class="content-background">
      <h3>充值</h3>
      <img src="../../assets/images/OrderDetailback.png" alt="" class="back-person">
      <div class="dialog-content">
        <input type="number" v-model="rechargeAmount" placeholder="输入充值金额" />
        <button @click="confirmRecharge" class="redbtn">确认充值</button>
      </div>
    </div>
   </div>

   <!-- 提现弹窗 -->
    <div v-if="showWithdraw" class="dialog-wrapper">
      <div class="dialog-background" @click="hideWithdrawDialog"></div>
      <div class="content-background">
        <h3>提现</h3>
        <img src="../../assets/images/OrderDetailback.png" alt="" class="back-person">
        <div class="dialog-content">
          <input type="number" v-model="withdrawAmount" placeholder="输入提现金额" />
          <button @click="confirmWithdraw" class="bluebtn">确认提现</button>
        </div>
      </div>
    </div>
</template>
<script setup lang="ts">
import {ref,reactive, onMounted, onUnmounted} from "vue"
import { useRouter } from "vue-router";
import { useTokenStore } from "../../stores/Login";
import { getUserBalance  } from "../../api/Person/index";
import defaultAvatar from '../../assets/images/icon.png';
import { rechargeBalance,deductBalance } from "../../api/Person/index";

const {user} = useTokenStore()
const tokenStore = useTokenStore()
const router = useRouter();
const logined = ref<boolean>(false)
const avatarUrl = ref<string>('')
const nickname = ref<string>('')
const balance = ref<number>(user.balance)
const showRecharge = ref<boolean>(false);
const showWithdraw = ref<boolean>(false);
const rechargeAmount = ref<number>();
const withdrawAmount = ref<number>();

// const fetchBalance = async () => {
//   try {
//     const response = await getUserBalance(user.userId);
//     balance.value = response.data.data;
//     const storedUser = localStorage.getItem('user');
//     if (storedUser) {
//       const userData = JSON.parse(storedUser).user;
//       userData.balance = balance.value;
//       localStorage.setItem('user', JSON.stringify({ user: userData }));
//     }
//   } catch (error) {
//     console.error("获取余额失败:", error);
//   }
// };


// 判断是否登录
onMounted(()=>{
  if (user.token) {
    logined.value = true;
    const storedUser = localStorage.getItem('user');
    if (storedUser) {
      const userData = JSON.parse(storedUser).user; // 解析用户信息
      avatarUrl.value = userData.avatarUrl ; // 提取头像 URL
      nickname.value = userData.username; // 提取昵称
      balance.value = userData.balance; // 提取余额
    }
  } else {
    logined.value = false;
  }
  
})

// 显示充值弹窗
const showRechargeDialog = () => {
  showRecharge.value = true;
};

//显示提现弹窗
const showWithdrawDialog = () => {
  showWithdraw.value = true;
};

// 隐藏充值弹窗
const hideRechargeDialog = () => {
  showRecharge.value = false;
};

// 隐藏提现弹窗
const hideWithdrawDialog = () => {
  showWithdraw.value = false;
};

// 确认充值
const confirmRecharge = async () => {
  try {
      const response = await rechargeBalance(user.userId, rechargeAmount.value);
      if (response.data.code === 200) {
        user.balance += rechargeAmount.value;
        const storedUser = localStorage.getItem('user');
        if (storedUser) {
          const userData = JSON.parse(storedUser).user;
          userData.balance = user.balance;
          localStorage.setItem('user', JSON.stringify({ user: userData }));
        }
        hideRechargeDialog();
      } else {
        alert("充值失败：" + response.data.message);
      }
    } catch (error) {
      console.error("充值失败:", error);
      alert("充值失败，请稍后再试");
    }
};

// 确认提现
const confirmWithdraw = async() => {
  try {
      const response = await deductBalance(user.userId, withdrawAmount.value);
      if (response.data.code === 200) {
        user.balance -= withdrawAmount.value;
        const storedUser = localStorage.getItem('user');
        if (storedUser) {
          const userData = JSON.parse(storedUser).user;
          userData.balance = user.balance;
          localStorage.setItem('user', JSON.stringify({ user: userData }));
        }
        hideWithdrawDialog();
      } else {
        alert("提现失败：" + response.data.message);
      }
    } catch (error) {
      console.error("提现失败:", error);
      alert("提现失败，请稍后再试");
    }
};

// 跳转到登录界面
const gotologin =() =>{
  router.push('/login')
}

// 跳转到个人信息界面
const gotoPersonal = () =>{
  router.push('/personal')
}

// 跳转到地址界面
const gotoAddress = () =>{
  router.push('/address')
}

// 跳转到地址界面
const gotoFeedback = () =>{
  router.push('/feedback')
}

// 退出登录
const logout = () => {
  tokenStore.logout();
  logined.value = false;
  router.push('/mine');
};

</script>
<style lang="less" scoped>
.person-center{
  height: 291px;
  width: 100%;
  background-color: rgba(252, 30, 9, 0.8);
}

.person-center h3{
  color: #FFFFFF;
  text-align: center;
  padding-top: 15px;
}

.person-message{
  position: absolute;
  width: 99px;
  height: 168px;
  left: 50%;
  transform: translateX(-50%);
  margin-top: 22px;
}

.person-message img{
  width: 100px;
  height: 100px;
  border-radius: 50%;
  padding-bottom: 10px;
}

.person-message h4{
  color: #FFFFFF;
  text-align: center;
  font-size: 20px;
}

.money{
  width: 380px;
  height: 136px;
  position: absolute;
  background-color: #FFFFFF;
  left: 50%;
  transform: translateX(-50%);
  top: 240px;
  border-radius: 15px;
}

.money img{
  width: 34px;
}

.money-title {
  width: 311px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  margin-top: 8px;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  border-bottom: 1px solid #BBBBBB;
  padding-bottom: 7px;
}

.money-title .bao {
  margin: 0 10px; /* 调整文字与图标之间的间距 */
}

.money-body {
  width: 311px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  margin-top: 70px;
}

.addin, .putout {
  width: 80px;
  height: 36px;
  background-color: #FF8C00;
  color: #fff;
  border: none;
  border-radius: 10px;
  cursor: pointer;
}

.money-center {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.money-left {
  font-size: 24px;
  color: #F80606;
  // font-weight: bold;
}

.my {
  font-size: 15px;
  color: #888888;
}

.person-function{
  width: 380px;
  height: 330px;
  background-color: #FFFFFF;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  margin-top: 140px;
  padding-top: 40px;
  border-radius: 15px;
}

.function-item {
  height: 51px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 20px;
}

.function-item img {
  width: 24px;
  height: 24px;
}

.function-item span {
  flex: 1;
  margin-left: 10px;
  font-size: 16px;
  color: #333;
}

.unlogin {
  width: 223px;
  height: 255px;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  top: 30%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.unlogin img{
  width: 125px;
  margin-bottom: 15px;
}

.unlogin .des{
  font-size: 15px;
  color: #6C6C6C;
  margin-top: 10px;
  margin-bottom: 20px
}

.unlogin button{
  width: 129px;
  height: 48px;
  background-color: rgba(252, 30, 9, 0.8);
  color: #FFFFFF;
  border: none;
  border-radius: 4px;
}

.dialog-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */
}

.content-background {
  position: relative;
  width: 300px;
  height: 201px;
  background-color: #FFBF6B;
  border-radius: 40px 16px 16px 16px;
  padding-top: 65px;
}

.back-person{
  width: 183px;
  height: 119px;
  position: absolute;
  top: -40px;
  left: 160px;
}

.dialog-content {
  position:absolute;
  top: 65px;
  left: 10px;
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
  z-index: 1001;
  width: 80%;
  max-width: 400px;
  height: 145px;
  text-align: center;
}

.content-background h3{
  color: #D37902;
  font-size: 24px;
  margin-left: 20px;
  position:absolute;
  top: 20px;
  left: 40px;
}

.dialog-content input {
  width: 80%;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 15px;
    margin: 30px 13px 20px;
}

.dialog-content .redbtn {
  padding: 10px 20px;
  background-color: #f56c6c;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
.dialog-content .bluebtn {
  padding: 10px 20px;
  background-color: #4095E5;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

</style>
